<script setup lang="ts" name="SystemDepart">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { getIntDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/enums/dictEnums'
import { DepartApi } from '@/api/system/depart/index'
import { UserApi, UserType } from '@/api/system/user/index'
import DepartForm from './DepartForm.vue'
import { checkPermit, computedOperateWidth } from '@/utils/permit'
import { handleTree } from '@/utils/tree'
import  { cloneDeep } from 'lodash-es'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const isExpandAll = ref(false) // 是否展开，默认全部折叠
const dataList = ref<any>([]) // 部门原始数据
const list = ref<any>([]) // 部门表格树结构数据
const queryLoading = ref(false) // 列表加载中：1）列表数据加载；2）查询按钮禁用；3）重置按钮禁用
const refreshTable = ref(true) // 重新渲染表格状态
const userList = ref<UserType[]>([]) // 用户列表
const queryParams = ref({
  name: '',
  status: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询部门列表 */
const getList = async () => {
  queryLoading.value = true
  try {
    const data = await DepartApi.list()
    dataList.value = cloneDeep(data)
    list.value = handleTree(data)
  } finally {
    queryLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  refreshTable.value = false
  list.value = []
  const res = cloneDeep(dataList.value)
  const result = res.filter(item => {
    return (item.name === '' ? true : item.name.indexOf(queryParams.value.name) !== -1) && (queryParams.value.status === undefined ? true : item.status === queryParams.value.status)
  })
  let arr = cloneDeep(result)
  const getParent = (item) => {
    if (item.parentId !== 0) {
      const parent = res.find(v => v.id === item.parentId)
      const hasParent = arr.some(v => v.id === parent.id)
      if (!hasParent) {
        arr.push(parent)
      }
      getParent(parent)
    }
  }
  result.forEach(item => {
    getParent(item)
  })
  list.value = handleTree(arr)
  isExpandAll.value = true
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.name = ''
  queryParams.value.status = undefined
  list.value = handleTree(dataList.value)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, parentId?: number) => {
  formRef.value.open(type, id, parentId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DepartApi.delete(id)
    message.success(t('message.del', 'success'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 获取用户列表
  userList.value = await UserApi.simple()
})
</script>

<template>
  <PageCard>
    <ContentFormTable>
      <template #header>
        <ElForm ref="queryFormRef" :model="queryParams" :inline="true">
          <ElFormItem :label="t('sys.depart', 'name')" prop="name" class="!w-240px">
            <el-input v-model="queryParams.name" :placeholder="t('sys.depart.rules', 'name')" clearable @keyup.enter="handleQuery" />
          </ElFormItem>
          <ElFormItem :label="t('common', 'status')" prop="status">
            <el-select v-model="queryParams.status" class="!w-160px" clearable :placeholder="t('sys.depart.rules', 'status')" @change="handleQuery">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </ElFormItem>
          <ElFormItem>
            <el-button type="primary" :disabled="queryLoading" icon="Search" @click="handleQuery">{{ t('action', 'search') }}</el-button>
            <el-button icon="Refresh" :disabled="queryLoading" @click="resetQuery">{{ t('action', 'reset') }}</el-button>
            <el-button v-if="checkPermit(['system:menu:create'])" type="success" icon="Plus" @click="openForm('create')">{{ t('action', 'create') }}</el-button>
            <el-button type="danger" icon="sort" @click="toggleExpandAll">{{ t('sys.menu', 'expand') }}</el-button>
          </ElFormItem>
        </ElForm>
      </template>
      <template #content>
        <el-table v-if="refreshTable" v-loading="queryLoading && systemConfig.loadingType === 'module'" :data="list" :default-expand-all="isExpandAll" row-key="id" border>
          <el-table-column type="index" :label="t('common', 'index')" width="60" align="center" fixed="left" />
          <el-table-column prop="name" :label="t('sys.depart', 'name')" show-overflow-tooltip min-width="180" fixed="left" />
          <el-table-column prop="leader" :label="t('sys.depart', 'leader')" align="center">
            <template #default="scope">
              {{ userList.find((user) => user.id === scope.row.leaderUserId)?.nickname }}
            </template>
          </el-table-column>
          <el-table-column prop="phone" :label="t('sys.depart', 'phone')" align="center" />
          <el-table-column prop="email" :label="t('sys.depart', 'email')" align="center" />
          <el-table-column prop="sort" :label="t('common', 'sort')" width="60" align="center" />
          <el-table-column prop="status" :label="t('common', 'status')" width="90" align="center">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column prop="remark" :label="t('common', 'remark')" show-overflow-tooltip align="center" />
          <el-table-column v-if="checkPermit(['system:depart:create', 'system:depart:update', 'system:depart:delete'])" prop="operate" :label="t('common', 'operate')" :width="computedOperateWidth(['system:menu:create', 'system:menu:update', 'system:menu:delete'])" fixed="right">
            <template #default="scope">
              <el-button v-if="checkPermit(['system:depart:update'])" type="primary" icon="Edit" @click="openForm('update', scope.row.id, scope.row.parentId)" />
              <el-button v-if="checkPermit(['system:depart:delete'])" type="danger" icon="Delete" @click="handleDelete(scope.row.id)" />
              <el-button v-if="checkPermit(['system:depart:create'])" type="success" icon="Plus" @click="openForm('create', undefined, scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <DepartForm ref="formRef" @success="getList" />
      </template>
    </ContentFormTable>
  </PageCard>
</template>

<style scoped lang="scss">
.el-table {
  width: 100%;
  height: 100%;
}
</style>
